package com.cscp.javastudy.juc.functionalprogramming.optional;

import com.cscp.javastudy.juc.functionalprogramming.stream.Author;

import java.util.Optional;

public class OptionalDemo1 {


    public static void main(String[] args) {
        // Demo1 ofNullable()
//        Optional<Author> authorOptional = getAuthorOptional1();
//        authorOptional.ifPresent(author -> System.out.println(author.getName()));

        // Demo2 of() 不推荐使用
//        Optional<Author> authorOptional = getAuthorOptional2();
//        authorOptional.ifPresent(author -> System.out.println(author.getName()));

        // Demo3 get() 不推荐使用
//        Optional<Author> authorOptional = getAuthorOptional3();
//        authorOptional.get();// java.util.NoSuchElementException: No value present

        // Demo4 orElseGet() 如果拿到的对象为null则返回后面的默认值
//        Optional<Author> authorOptional = getAuthorOptional3();
//        Author author = authorOptional.orElseGet(() -> new Author(1L, "Jama", 33, "西安人", null));
//        System.out.println(author.getName());

        // Demo5 orElseThrow()
//        Optional<Author> authorOptional = getAuthorOptional3();
//        Author author = authorOptional.orElseThrow(() -> new RuntimeException("没有数据啦"));
//        System.out.println(author.getName());

        // Demo6 filter()
//        Optional<Author> authorOptional = getAuthorOptional3();
//        System.out.println(authorOptional.filter(author -> author.getAge() > 80));

        // Demo7 isPresent()
//        Optional<Author> authorOptional1 = getAuthorOptional1();
//        if (authorOptional1.isPresent()) {
//            System.out.println(authorOptional1.get().getName());
//        }

        // Demo8 map()
        Optional<Author> authorOptional1 = getAuthorOptional1();
        authorOptional1.map(Author::getBooks)
                .ifPresent(books -> System.out.println(books));


    }


    /**
     * ofNullable()
     * 很常用的创建Optional对象的方法
     */
    public static Optional<Author> getAuthorOptional1(){
        Author author = new Author(1L, "Jama", 33, "西安人", null);
        return Optional.ofNullable(author);
    }

    /**
     * of() 不推荐使用
     * 使用此方法时请确保传入的对象不为null，如果为null或抛出空指针异常
     */
    public static Optional<Author> getAuthorOptional2(){
        Author author = new Author(1L, "Jama", 33, "西安人", null);
        return Optional.of(null);
    }

    /**
     * get() 不推荐使用
     * 获取对象
     */
    public static Optional<Author> getAuthorOptional3(){
        return Optional.ofNullable(null);
    }

    /**
     * filter()
     */
    public static Optional<Author> getAuthorOptional4(){
        return Optional.ofNullable(null);
    }

}


